// pages/other/preference/preference.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var timer, clickIndex = 0;
var app = getApp()
var winScale = 750 / app.data.deviceInfo.windowWidth;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mid: '0',// 场次ID
    need: '1',//是否需要请求场次数据
    page: 1,
    page_size: 10,
    showLoading: true,
    has_more: false,
    list_flag: false,
    currentIndex: 0, //当前场次 
    event_goods: [],
    has_event: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {//get_time_preference  http://sapi-test.shihanbainian.com/1/time_preference/index/mid_286/need_0/1-20.html
    this.getTimePreference();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  getTimePreference: function () {
    var that = this;
    shihan.sendRequest(config.get_time_preference + 'mid_' + that.data.mid + '/need_' + that.data.need + '/' + that.data.page + '-' + that.data.page_size + '.html', 'GET', {})
      .then(function (response) {
        //sh_is_start 场次状态：0 即将开始 1 正在抢购中 2 已结束
        if (response.data.code == 0) {
          var preference_products = response.data.data.sh_time_preference_products;
          if (preference_products && preference_products.sh_items && preference_products.sh_items.length>0) {
            preference_products.sh_items.forEach(function(el, index){
              if (el.sh_label.sh_location) {
                var pos = el.sh_label;
                pos['posa'] = pos.sh_location.split('_')[0];
                pos['posb'] = pos.sh_location.split('_')[1];
              }
            })
            that.setData({
              is_partner: response.data.args.is_partner,
              event_goods: that.data.event_goods.concat(preference_products.sh_items),
              has_more: true,
              list_flag: true
            })
            // console.log(that.data.event_goods)
          } else {
            that.setData({
              has_more: false,
              list_flag: false
            })
          }
          
          if (preference_products && preference_products.sh_total_rows) {
            if (that.data.event_goods.length == preference_products.sh_total_rows) {
              that.setData({
                has_more: false,
                list_flag: false
              })
            }
          } else {
            that.setData({
              has_more: false,
              list_flag: false
            })
          }
          if (that.data.page == 1 && that.data.need == 1) {
            if (response.data.data.sh_event_maps&&response.data.data.sh_event_maps.length>0) {
              response.data.data.sh_event_maps.forEach(function (el, index) {
                el['clock'] = {
                  preHour: '00',
                  preMinute: '00',
                  preSecond: '00',
                }
                if (el.sh_is_checked == 1) {
                  that.setData({
                    currentIndex: index
                  })
                  clickIndex = index;
                }
              })
            }
            that.setData({
              need: 0,
              has_event: response.data.data.sh_has_event,
              event_maps: response.data.data.sh_event_maps,
              share_data: response.data.data.sh_share_data,
              banner_img: response.data.data.sh_top_img
            })
            setInterval(function () {
              that.data.event_maps.forEach((el, index) => {
                that.timeCalculation(el, index);
              })
            }, 1000);
          }
        }
        wx.stopPullDownRefresh()
        that.setData({
          showLoading: false
        })
      }, function (error) {
        console.log(error);
      });
  },

  changeMaps: function (e) {
    var index = e.currentTarget.dataset.index;
    if (clickIndex == index) {
      return
    }
    clickIndex = index;
    this.data.event_goods.length = 0;
    this.setData({
      need: 0,
      page: 1,
      showLoading: true,
      has_more: true,
      list_flag: true,
      event_goods: [],
      mid: this.data.event_maps[index].sh_id,
      currentIndex: index,
      scroll_left: ((index + 1) * 110 - 55 - 375) / winScale
    })
    this.getTimePreference();
  },

  timeCalculation: function (map, index) { //sh_create_at:"2017-08-28 16:23:26" 特惠时间计算
    var that = this;
    var time1 = new Date().getTime();
    var time2 = new Date(map.sh_start_time.replace(/-/g, '/'));
    var time3 = new Date(map.sh_end_time.replace(/-/g, '/'));

    if ((time1 - time2 > 0) && (time3 - time1 > 0)) { //正在进行中
      var micro_second = time3 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      that.data.event_maps[index]['clock'] = {
        preHour: hour,
        preMinute: minute,
        preSecond: second
      }
    } else if ((time1 - time2 < 0) && (time1 - time3 < 0)) { //即将开始 activitytime: '',
      var micro_second = time2 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      that.data.event_maps[index]['clock'] = {
        preHour: hour,
        preMinute: minute,
        preSecond: second
      }
    } else {
      that.data.event_maps[index]['clock'] = {
        preHour: '00',
        preMinute: '00',
        preSecond: '00',
      }
    }
    that.setData({
      event_maps: that.data.event_maps
    })
  },

  openGoodsdetail: function (e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },

  setReminder: function (e) { //set_preference_reminder
    var id = e.currentTarget.dataset.id;
    var that = this;
    shihan.sendRequest(config.set_preference_reminder, 'POST', { product_id: id })
      .then(function (response) {
        if (response.data.code == 0) {
          shihan.showToast.call(that, '设置成功,开抢后我们将会短信提醒你', 3);
        } else {
          shihan.showToast.call(that, response.data.msg);
        }
      }, function (error) {
        console.log(error);
      });
    return
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.event_goods.length = 0;
    this.setData({
      page: 1,
      need: 1,
      mid: this.data.mid,
      event_goods: [],
      showLoading: true,
      has_more: true,
      list_flag: true
    })
    this.getTimePreference();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.list_flag) {
      this.setData({
        list_flag: false,
        page: this.data.page + 1
      })
      this.getTimePreference();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.share_data.sh_program_title,
      path: that.data.share_data.sh_program_url,
      imageUrl: that.data.share_data.sh_program_image,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})